<template>
	<view class="page-content">
		<view class="mt-20 bg_fff pd-20">
			<u--form labelPosition="left" ref="form1" labelWidth="50">
				<u-form-item label="头像" prop="infoData.headimg" borderBottom ref="item1">
					<button class="button mbutton" open-type="chooseAvatar" @chooseavatar="onChooseAvatar"
						style="width: 100%;height: 80rpx;background-color: #fff;padding: 0px;margin: 0px;text-align: right;">
						<image class="avatar" style="width: 80rpx;height: 80rpx;"
							:src="infoData.headimg == '' ? 'https://dtkj-qnyimg.diankuai.com/%E6%88%91%E7%9A%84/AgAACt9b6bHCBS7_MHZLx42fxbCRZ4xx.png' : infoData.headimg">
						</image>
					</button>
				</u-form-item>
				<u-form-item label="姓名" prop="infoData.username" borderBottom ref="item1">
					<!-- <u--input v-model="infoData.username" type="nickname" inputAlign="right" border="none"
						placeholder="请输入姓名">
					</u--input> -->
					<input type="nickname" v-model="infoData.username" placeholder="请输入姓名" style="text-align: right;"
						@blur="nameView" />
				</u-form-item>
				<u-form-item label="手机号" prop="infoData.phone" borderBottom ref="item1">
					<u--input v-model="infoData.phone" inputAlign="right" type="number" border="none"
						placeholder="请输入手机号" :disabled="checkPhone" disabledColor="#fff"></u--input>
				</u-form-item>
				<u-form-item label="性别" prop="infoData.base_sex" borderBottom ref="item2">
					<u-radio-group v-model="infoData.base_sex">
						<u-radio :customStyle="{marginRight: '16px'}" v-for="(item, index) in sexList" :key="index"
							:label="item.name" :name="item.name">
						</u-radio>
					</u-radio-group>
				</u-form-item>
				<!-- 	<u-form-item label="生日" prop="infoData.base_birthday" borderBottom
					@click="showBirthday = true; hideKeyboard()" ref="item1">
					<u--input v-model="infoData.base_birthday" inputAlign="right" disabled disabledColor="#ffffff"
						placeholder="请选择生日" border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item> -->
				<!-- <u-form-item label="地区" prop="infoData.area" borderBottom @click="showPicker = true; hideKeyboard()"
					ref="item1">
					<uni-data-picker :localdata="regionData" :map="{text:'name',value:'name'}" popup-title="请选择地区"
						v-model="infoData.area" @change="onchange"></uni-data-picker>
				</u-form-item> -->
				<u-form-item label="地址" prop="infoData.address" borderBottom>
					<u--input v-model="infoData.address" border="none" placeholder="地址"></u--input>
					<u-button slot="right" @tap="getMapLocation" text="选择地址" type="success" size="mini">
					</u-button>
				</u-form-item>
			</u--form>
		</view>
		<view class="position_bottom btmBox c_ffffff" @click="doSub">
			保存
		</view>
		<u-datetime-picker :show="showBirthday" :value="birthday" mode="date" closeOnClickOverlay
			@confirm="birthdayConfirm" @cancel="birthdayClose" @close="birthdayClose" :minDate="315504000000">
		</u-datetime-picker>
		
		<m-login ref="login" :zIndex="1000000000" @success="loginRes" @error="loginError"></m-login>
	</view>
</template>

<script>
	import {
		getRegion,
		postUserInfo
	} from '@/config/api.js'

	export default {
		data() {
			return {
				capture: ['album', 'camera'],
				sexList: [{
					name: "男"
				}, {
					name: "女"
				}],
				showCalendar: false,
				showBirthday: false,
				showPicker: false,
				regionData: [],
				infoData: {
					username: "",
					base_sex: "男",
					base_birthday: "",
					phone: "",
					headimg: "",
					address: ""
				},
				fileList: [],
				checkPhone: true
			}
		},
		onLoad() {
			this.$refs.login.checkLogin();
			this.getRegionData();
			this.infoData = uni.getStorageSync('UserInfo');
			this.infoData.area = [];

			this.fileList = [{
				url: this.infoData.headimg
			}];

			if (this.infoData) {
				if (this.infoData.region_province) {
					this.infoData.area.push(this.infoData.region_province);
				}
				if (this.infoData.region_city) {
					this.infoData.area.push(this.infoData.region_city);
				}
				if (this.infoData.region_area) {
					this.infoData.area.push(this.infoData.region_area);
				}

				if (this.infoData.phone == "") {
					this.checkPhone = false;
				}
			}
		},
		options: {
			styleIsolation: 'shared'
		},
		methods: {
			async onChooseAvatar(e) {
				const avatarUrl = e.detail.avatarUrl // 此处是头像的临时路径
				const result = await this.uploadFilePromise(avatarUrl);
				if (result.code == 1) {
					this.infoData.headimg = result.data.url;
				}
			},
			deletePic() {
				this.fileList = [];
			},
			async afterRead(event) {
				this.fileList = [{
					...event.file,
					status: 'uploading',
					message: '上传中'
				}];
				const result = await this.uploadFilePromise(this.fileList[0].url);

				if (result.code == 1) {
					this.infoData.headimg = result.data.url;
					this.fileList[0] = Object.assign(this.fileList[0], {
						status: 'success',
						message: '',
						url: result.data.url
					});
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: 'https://dtkj.diankuai.com/data/api.auth.center/image', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						header: {
							'Api-Name': 'wxapp',
							'Api-Token': uni.getStorageSync('UserToken'),
							'Content-Type': 'application/x-www-form-urlencoded'
						},
						success: (res) => {
							setTimeout(() => {
								resolve(JSON.parse(res.data))
							}, 1000)
						}
					});
				})
			},
			onchange(e) {
				this.infoData.area = [];

				if (e.detail.value[0]) {
					this.infoData.area.push(e.detail.value[0].value);
				}

				if (e.detail.value[1]) {
					this.infoData.area.push(e.detail.value[1].value);
				}

				if (e.detail.value[2]) {
					this.infoData.area.push(e.detail.value[2].value);
				}
			},
			doSub() {
				postUserInfo(this.infoData).then(res => {
					this.infoData = res;
					this.infoData.area = [];
					if (res.region_province) {
						this.infoData.area.push(res.region_province);
					}
					if (res.region_city) {
						this.infoData.area.push(res.region_city);
					}
					if (res.region_area) {
						this.infoData.area.push(res.region_area);
					}

					uni.setStorageSync('UserInfo', res || {});
					uni.showToast({ //提示
						title: '操作成功！'
					})

					uni.switchTab({
						url: "/pages/tabbar/tabbar-1/tabbar-1"
					})
				}).catch(err => {

				})
			},
			getRegionData() {
				getRegion().then(res => {
					this.regionData = res;
				}).catch(err => {

				})
			},
			onnodeclick(e) {
				console.log(e);
			},
			birthdayClose() {
				this.showBirthday = false
			},
			birthdayConfirm(e) {
				this.showBirthday = false
				this.infoData.base_birthday = uni.$u.timeFormat(e.value, 'yyyy-mm-dd')
			},
			hideKeyboard() {
				uni.hideKeyboard()
			},
			getMapLocation() {
				var that = this;
				uni.chooseLocation({
					success: (res) => {
						that.infoData.address = res.address;
					},
					fail: () => {
						// 如果用uni.chooseLocation没有获取到地理位置，则需要获取当前的授权信息，判断是否有地理授权信息          
						uni.getSetting({

							success: (res) => {
								console.log(res);
								var status = res.authSetting;
								if (!status['scope.userLocation']) {
									// 如果授权信息中没有地理位置的授权，则需要弹窗提示用户需要授权地理信息           
									uni.showModal({
										title: "是否授权当前位置",
										content: "需要获取您的地理位置，请确认授权，否则地图功能将无法使用",
										success: (tip) => {

											if (tip.confirm) {
												// 如    
												uni.openSetting({
													success: (data) => {
														// 如果用户授权了地理信息在，则提示授权成功                                     
														if (data
															.authSetting[
																'scope.userLocation'
															] === true
														) {
															uni.showToast({
																title: "授权成功",
																icon: "success",
																duration: 1000
															})
															// 授权成功后，然后再次chooseLocation获取信息 

															uni.chooseLocation({
																success: (
																	res
																) => {
																	that.infoData
																		.address =
																		res
																		.address;
																}

															})

														} else {
															uni.showToast({
																title: "授权失败",
																icon: "none",
																duration: 1000
															})
														}
													}
												})
											}
										}
									})
								}
							},
							fail: (res) => {
								uni.showToast({
									title: "调用授权窗口失败",
									icon: "none",
									duration: 1000
								})
							}
						})
					}
				});
			}
		}
	}
</script>

<style scoped>
	.btmBox {
		background: linear-gradient(to bottom, #C62B2C, #FF7C71);
		border-radius: 40rpx;
		line-height: 80rpx;
		text-align: center;
		font-size: 40rpx;
		font-weight: 600;
		box-sizing: border-box;
		margin-left: 5%;
		width: 90%;
		bottom: 120rpx;
	}

	/deep/ .selected-area.placeholder {
		color: #c0c4cc !important;
		font-size: 15px !important;
	}

	/deep/ .input-value.input-value-border {
		height: 24px !important;
		padding: 0px !important;
		border: none;
	}

	/deep/ .u-radio-group {
		justify-content: flex-end;
	}

	/deep/ .selected-list {
		justify-content: flex-end;
	}

	/deep/ .u-upload__wrap__preview__image,
	/deep/ .u-upload__button {
		border-radius: 50%;
		width: 80rpx !important;
		height: 80rpx !important;
	}

	/deep/ .u-upload__wrap {
		justify-content: flex-end;
		margin: 0;
	}

	/deep/ .u-upload__wrap__preview {
		margin: 0 !important;
	}

	.mbutton::after {
		border-color: transparent !important;
	}
</style>
